package com.atguigu.daijia.dispatch.xxl.job;

import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.atguigu.daijia.dispatch.mapper.OrderJobMapper;
import com.atguigu.daijia.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.daijia.dispatch.service.NewOrderService;
import com.atguigu.daijia.model.entity.dispatch.XxlJobLog;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class JobHandler {

    @Resource
    private NewOrderService newOrderService;
    @Resource
    private XxlJobLogMapper xxlJobLogMapper;

    @XxlJob("firstJobHandler")
    public void firstJobHandler() {
        log.info("xxl-job项目集成测试");
    }

    // 定义一个名为newOrderTaskHandler的定时任务处理器
    @XxlJob("newOrderTaskHandler")
    public void newOrderTaskHandler(){
        // 记录日志：当前执行的新调度任务及任务ID
        log.info("新调度任务：{}", XxlJobHelper.getJobId());

        // 初始化一个XxlJob日志对象，用于记录任务执行信息
        XxlJobLog xxlJobLog = new XxlJobLog();
        // 设置任务ID
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        // 记录任务开始时间
        long startTime = System.currentTimeMillis();
        try{
            // 执行新订单服务的任务，传入任务ID
            newOrderService.executeTask(XxlJobHelper.getJobId());
            // 任务执行成功，设置任务状态为1（成功）
            xxlJobLog.setStatus(1);
        }catch (Exception e){
            // 任务执行失败，设置任务状态为0（失败）
            xxlJobLog.setStatus(0);
            // 记录异常信息
            xxlJobLog.setError(ExceptionUtil.getAllExceptionMsg(e));
            // 记录错误日志，任务执行失败
            log.error("定时任务执行失败：{},任务id为", XxlJobHelper.getJobId());
            // 打印异常栈信息
            e.printStackTrace();
        }finally {
            // 计算任务执行时间，并记录到日志对象中
            xxlJobLog.setTimes((int)(System.currentTimeMillis() - startTime));
            // 将任务日志插入数据库，保存任务执行信息
            xxlJobLogMapper.insert(xxlJobLog);
        }
    }

}
